import React, {useEffect, useState} from 'react'
import {Button, message, Space} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect} from 'umi'
import {ArrowDownOutlined, ArrowUpOutlined} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import {translateDataToTree} from '@/utils/common'
import {getAllCitys, getCompany} from '@/service/common'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {getAllChannelType} from '@/service/merchantCenter/rewardDetails'
import {downloadDocumentUrl} from '@/service/common/download'
import {getFirstChannelType} from '@/service/channel'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {formatDate} from '@/utils/common/dateFilter'
import {
	ditchreplenishImport,
	getDitchreplenishList,
	getErrorRulesPage,
} from '@/service/merchantCenter/deduction'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {rewardsType} from '../../dict'

interface DataType {
	showArchivesAuditButton: any
	showEditButton: any
	archivesInstanceId: string
	id: string | string[] | null
	supplierCode: string
	supplierName: string
	orgId: string
	serviceType: string
	number: string
	contacts: string
	status: number
	date: string
}

const formItemLayout = {
	labelCol: {flex: '140px'},
	wrapperCol: {flex: '1'},
}

const rewardDetails = (props: {
	user: {orgId: string | number; userId: string | number}
}) => {
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [companyData, setCompanyData] = useState([]) // 公司数据
	const [subjectList, setSubjectList] = useState([]) // 获取主体数据
	const [citysList, setCitysList] = useState([]) // 城市数据
	const [firstChannelData, setFirstChannelData] = useState([]) // 一级渠道类型
	const [secondChannelData, setSecondChannelData] = useState<any[]>([]) // 二级渠道类型
	const [loading, setLoading] = useState<boolean>(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)

	/** 获取主体数据 */
	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res?.data)
			}
		})
	}
	/** 获取一级渠道类型 */
	const getFirstChannelTypeFun = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.success) {
				setFirstChannelData(() => res?.data)
			}
		})
	}
	/** 获取二级渠道类型 */
	const getAllChannelTypeFun = () => {
		getAllChannelType().then((res: any) => {
			if (res?.success) {
				const arr: any[] = []
				res?.data?.forEach((item: any) => {
					item?.secondChannelType.forEach((items: any) => {
						arr.push(items)
					})
				})
				setSecondChannelData(arr)
			}
		})
	}

	// 获取公司列表
	const onCompany = () => {
		getCompany({merchantId: props.user.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props.user.orgId])
	useEffect(() => {
		getSubjectFun()
		getCitysFun()
		getAllChannelTypeFun()
		getFirstChannelTypeFun()
	}, [])

	// 获取补扣费明细列表
	const getData = () => {
		setLoading(true)
		getDitchreplenishList({
			...params,
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				} 
			})
			.catch(() => {
				setDataSourse([])
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	const columns: ColumnsType<DataType> = [
		{
			title: '补扣费编码',
			dataIndex: 'replenishNo',
			align: 'center',
			width: 120,
		},
		{
			title: '费用发生月份',
			dataIndex: 'expenseMouth',
			align: 'center',
			width: 160,
		},
		{
			title: '奖励发生时间',
			dataIndex: 'rewardOccurrenceDate',
			align: 'center',
			width: 160,
		},
		{
			title: '主体',
			dataIndex: 'subjectName',
			align: 'center',
			width: 120,
		},
		{
			title: '公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 120,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 120,
		},
		{
			title: 'AMC一级渠道类型',
			dataIndex: 'firstLevelTypeStr',
			align: 'center',
			width: 150,
		},
		{
			title: 'AMC二级渠道类型',
			dataIndex: 'secondLevelTypeStr',
			align: 'center',
			width: 150,
		},
		{
			title: '渠道id',
			dataIndex: 'ditchId',
			align: 'center',
			width: 120,
		},
		{
			title: '渠道名称',
			dataIndex: 'ditchName',
			align: 'center',
			width: 120,
		},
		{
			title: '类型',
			dataIndex: 'rewardsType',
			align: 'center',
			width: 120,
			render: (text) => (
				<>
					{rewardsType?.map((item) => {
						if (item?.key === text) {
							return item?.label
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '补费总金额',
			dataIndex: 'replenishCost',
			align: 'center',
			width: 150,
		},
		{
			title: '补费拉新量',
			dataIndex: 'replenishCount',
			align: 'center',
			width: 180,
		},
		{
			title: '补费总期数',
			dataIndex: 'replenishTerm',
			align: 'center',
			width: 120,
		},
		{
			title: '单期拉新费',
			dataIndex: 'pullFee',
			align: 'center',
			width: 120,
			render: (text) => (text < 0 ? 0 : text),
		},
		{
			title: '补费理由',
			dataIndex: 'replenishReason',
			align: 'center',
			width: 120,
		},
		{
			title: '审核状态',
			dataIndex: 'supplementaryCostStatusStr',
			align: 'center',
			width: 120,
		},
		{
			title: '审核时间',
			dataIndex: 'checkTime',
			align: 'center',
			width: 120,
		},
		{
			title: '申请人',
			dataIndex: 'createUserName',
			align: 'center',
			width: 120,
		},
		{
			title: '申请提交时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 140,
		},
		{
			title: '备注',
			dataIndex: 'remark',
			align: 'center',
			width: 200,
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '渠道名称',
					name: 'ditchName',
					key: 'ditchName',
				},
				{
					type: 'select',
					label: 'AMC一级渠道类型',
					name: 'firstLevelType',
					key: 'firstLevelType',
					keys: 'type',
					title: 'valueName',
					items: firstChannelData,
				},
				{
					type: 'select',
					label: 'AMC二级渠道类型',
					name: 'secondLevelType',
					key: 'secondLevelType',
					keys: 'value',
					title: 'valueName',
					items: secondChannelData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'dateRange',
					key: 'costTime',
					name: 'costTime',
					label: '费用发生日期',
				},
				{
					type: 'dateRange',
					key: 'checkTime',
					name: 'checkTime',
					label: '审核时间',
				},
				{
					type: 'select',
					key: 'supplementaryCostStatus',
					name: 'supplementaryCostStatus',
					label: '审核状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 0,
							text: '无补扣',
						},
						{
							value: 1,
							text: '待审核',
						},
						{
							value: 2,
							text: '审核中',
						},
						{
							value: 3,
							text: '审核通过',
						},
						{
							value: 4,
							text: '审核拒绝',
						},
					],
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					key: 'subjectId',
					name: 'subjectId',
					label: '主体',
					keys: 'id',
					title: 'merchantName',
					items: subjectList,
				},
				{
					type: 'treeSelect',
					key: 'orgId',
					name: 'orgId',
					label: '公司',
					keys: 'id',
					title: 'name',
					treeData: companyData,
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
					items: [...citysList],
				},
			],
		},
	]
	const onFinish = (values: any) => {
		const {costTime, checkTime, cityId, ...info} = values
		const startTime = formatDate(costTime?.[0], 'YYYY-MM-DD')
		const endTime = formatDate(costTime?.[1], 'YYYY-MM-DD')
		const checkStartTime = formatDate(checkTime?.[0], 'YYYY-MM-DD')
		const checkEndTime = formatDate(checkTime?.[1], 'YYYY-MM-DD')
		setSearchData({
			...info,
			cityId: cityId?.[1],
			startTime,
			endTime,
			checkStartTime,
			checkEndTime,
		})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}
	const errorColumns: ColumnsType<DataType> = [
		{
			title: '费用发生月份',
			dataIndex: 'expenseMouth',
			align: 'center',
			width: 120,
		},
		{
			title: '渠道ID',
			dataIndex: 'ditchId',
			align: 'center',
			width: 150,
		},
		{
			title: '渠道名称',
			dataIndex: 'ditchName',
			align: 'center',
			width: 150,
		},
		{
			title: '失败原因',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
		},
	]

	return (
		<div className={styles.deduction}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_merchantCenter_deduction_import">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => setIsUploadModalOpen(true)}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_merchantCenter_deduction_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '174',
										queryDesc:
											'补扣费明细表导出,resourceId:174',
										queryParam: searchData,
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={ditchreplenishImport}
				onTableList={getErrorRulesPage}
				getListData={getData}
				fileNmae="excel"
				modular="material"
				type={1}
				saveType={2}
				uploadFileUrl={`${modalApi.sales}/ditchreplenish/ditchreplenishImport`}
				columns={errorColumns}
				sourceId={43}
				templateType="渠道补扣费导入模板"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(rewardDetails)
